package spynx.net.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import spynx.net.ICookieManager;

public class CookieManager implements ICookieManager {
	
	private String cookieFolder = ".";
	private URL lastQuery = null;
	private List<Cookie> cookies;
	
	@Override
	public String getCookies(URL query) {
		StringBuilder cookiesStr = new StringBuilder();
		loadCookieFile(query);
		for(Cookie cookie: this.cookies)
			cookiesStr.append(cookie.getValue() + "; ");
		return cookiesStr.toString();
	}

	private String resolveCookieFile(URL query) {
		return new File(cookieFolder + "/" + query.getHost() + ".txt").getAbsolutePath();
	}
	
	private List<Cookie> loadCookieFile(URL query) {
		if (lastQuery == null || !lastQuery.getHost().equals(query.getHost())) {
			if (cookies == null)
				cookies = new ArrayList<Cookie>();
			else {
				saveCookieFile();
				cookies.clear();
			}
			String cookieFile = resolveCookieFile(query);
			try {
				if (new File(cookieFile).exists()) {
					BufferedReader reader = new BufferedReader(new FileReader(cookieFile));
					String line;
					while ((line = reader.readLine()) != null) {
						line = line.trim();
						if (line.length() > 0) {
							Cookie cookie = new Cookie(line);
							cookies.add(cookie);
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		lastQuery = query;
		return cookies;
	}

	@SuppressWarnings("unused")
	protected void saveCookieFile() {
		if (lastQuery == null)
			return;
		String cookieFile = resolveCookieFile(lastQuery);
		try {
			PrintStream ostream = new PrintStream(cookieFile);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void addCookie(URL query, String cookie) {
		loadCookieFile(query);
		cookies.add(new Cookie(cookie));
		saveCookieFile();
	}

	public void setCookieFolder(String cookieFolder) {
		this.cookieFolder = cookieFolder;
	}

	public String getCookieFolder() {
		return cookieFolder;
	}

}
